package com.adminlab.managers
{
	import com.adminlab.vos.Exam;
	import com.adminlab.vos.ExamType;
	import com.adminlab.vos.ExamTypeSummary;
	import com.adminlab.vos.Report;
	import com.adminlab.vos.ReportSummary;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import flashx.textLayout.utils.CharacterUtil;
	
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.controls.Alert;
	import mx.utils.StringUtil;
	
	import org.evil.asstream.AsStream;

	public class PersistenceManager
	{
		public var dataDirectory:File;
		public var tablesDirectory:File;
		
		public function PersistenceManager()
		{
			var dataDirectoryUrl:String = File.documentsDirectory.nativePath + File.separator + "AdminLab" + 
				File.separator + "data";
			dataDirectory = new File( dataDirectoryUrl );
			var tablesDirectoryUrl:String = File.documentsDirectory.nativePath + File.separator + "AdminLab" + 
				File.separator + "tables";
			tablesDirectory = new File( tablesDirectoryUrl );

		}
		
		public function clearDataDirectory():void
		{
			if( dataDirectory.exists )
			{
				if( dataDirectory.isDirectory )
				{
					dataDirectory.deleteDirectory( true );
				} else
				{
					dataDirectory.deleteFile();
				}	
				
			}	
		}	
		
		private function getReportFile( report:Report ):File
		{
			var url:String = dataDirectory.nativePath +  
				File.separator + 
				report.name + "-" +
				report.docthor + "-" + 
				report.created.time.toString() +
				( report.number ? "-" + report.number : "" ) +
				".xml";
			
			return( new File( url ) );
		}
		
		public function saveReport( report:Report ):Boolean
		{
			try
			{
				var fileReport:File= report.fileReport;
				
				if( fileReport && fileReport.exists )
					fileReport.deleteFile();
				
				fileReport = getReportFile( report ); 
				
				var fileStreamReport:FileStream = new FileStream();
				fileStreamReport.open( fileReport, FileMode.WRITE );
				var asStream:AsStream = new AsStream();
				var xmlReport:XML = asStream.toXml( report );
				
				fileStreamReport.writeUTF( xmlReport.toString() );
				fileStreamReport.close();
				return true;
				
			} catch ( e:Error )
			{
				Alert.show( e.toString(), "Error al crear archivo" );
			}	
			
			return false;
		}

		public function deleteReport( reportSummary:ReportSummary ):void
		{
			var fileReport:File= reportSummary.fileReport;
			
			if( fileReport && fileReport.exists )
			{
				fileReport.deleteFile();
			}
		}
		
		public function getReport( reportSummary:ReportSummary ):Report
		{
			try
			{
				var fileReport:File= reportSummary.fileReport;
				
				if( !fileReport || !fileReport.exists )
				{
					Alert.show( "No se encontro el archivo: " + 
						reportSummary.name + "-" +
						reportSummary.docthor + "-" + 
						reportSummary.created.time.toString() + "-" + 
						reportSummary.number +
						".xml");
					return null;
				} 	

				var fileStreamReport:FileStream = new FileStream();
				fileStreamReport.open( fileReport, FileMode.READ );
				
				var asStream:AsStream = new AsStream();
				var xmlReport:XML = new XML( fileStreamReport.readUTF() );
				
				var report:Report = asStream.fromXml( xmlReport ) as Report;
				//report.created = reportSummary.created;
				report.fileReport = reportSummary.fileReport; 
				
				
				fileStreamReport.close();
				
				report.saved = true;
				
				return report;
				
			} catch ( e:Error )
			{
				Alert.show( e.toString(), "Error al crear archivo" );
			}	
			
			return null;
			
		}	
	
		
		public function getReportList():ArrayCollection
		{
			var reportList:ArrayCollection = new ArrayCollection();
			
			try
			{
				var directoryListing:Array = dataDirectory.getDirectoryListing();
			} catch ( e:Error )
			{
				return reportList;
			}
			var reportSummary:ReportSummary;
			
			for( var i:int = 0; i < directoryListing.length; i++ )
			{
				var fileReport:File = directoryListing[ i ] as File;
				var fileNameParts:Array = fileReport.name.substr(0, fileReport.name.length - 4).split("-");
				reportSummary = new ReportSummary();
				reportSummary.fileReport = fileReport; 
				reportSummary.name = fileNameParts[0] as String;
				reportSummary.docthor = fileNameParts[1] as String;
				var createdString:String = String( fileNameParts[2] );
				var created:Date = new Date();
				created.setTime( new Number(createdString) );
				reportSummary.created = created;
				if( fileNameParts.length >= 4 )
				{
					var number:String = String( fileNameParts[3] );
					reportSummary.number = number;
				}
				reportList.addItem( reportSummary );
			}
			
			return reportList;
		}


		
		
		public function getExamTypeSummarys():ArrayCollection
		{
			var url:String = File.applicationDirectory.nativePath + 
				File.separator + "examTypes.csv";

			var fileExamTypes:File = new File( url );
			
			if( !fileExamTypes.exists )
				return null;
			
			var fileStreamExamType:FileStream = new FileStream();
			fileStreamExamType.open( fileExamTypes, FileMode.READ );
			
			var examTypeSummary:ExamTypeSummary = new ExamTypeSummary();
			var examTypes:ArrayCollection = new ArrayCollection();
			var isCode:Boolean = true;
			while( fileStreamExamType.bytesAvailable )
			{
				var intRead:int = fileStreamExamType.readByte();
				if( intRead == 0xd )
					intRead = fileStreamExamType.readByte();
				
				var read:String = String.fromCharCode( intRead );
					
				if( intRead == 0xa && fileStreamExamType.bytesAvailable )
				{
					isCode = true;
					examTypeSummary = new ExamTypeSummary();
					examTypes.addItem( examTypeSummary );
				}

				if( intRead != 0xa )
				{
					if( read == ";" )
					{
						isCode = false
					} else {
						if( isCode )
						{
							examTypeSummary.code += read;
						} else {
							examTypeSummary.name += read;
						}
							
					}
				}	

			}
			
			return examTypes;
		}

		public function saveExamType( examType:ExamType ):Boolean
		{
			try
			{
				var url:String = tablesDirectory.nativePath +  
					File.separator + 
					examType.code +	".xml";
				
				var fileExamType:File = new File( url );
				if( fileExamType.exists && examType.saved )
					fileExamType.deleteFile();
				
				var fileStreamExamType:FileStream = new FileStream();
				fileStreamExamType.open( fileExamType, FileMode.WRITE );
				var asStream:AsStream = new AsStream();
				var xmlExamType:XML = asStream.toXml( examType );
				
				fileStreamExamType.writeUTF( xmlExamType.toString() );
				fileStreamExamType.close();
				return true;
				
			} catch ( e:Error )
			{
				Alert.show( e.toString(), "Error al crear archivo" );
			}	
			
			return false;
		}

		public function getExamType( examTypeSummary:ExamTypeSummary ):ExamType
		{
			try
			{
				var url:String = tablesDirectory.nativePath +  
					File.separator + 
					examTypeSummary.code + ".xml";
				
				var fileExamType:File = new File( url );
				
				if( !fileExamType.exists )
					return null;
				
				var fileStreamExamType:FileStream = new FileStream();
				fileStreamExamType.open( fileExamType, FileMode.READ );
				
				var asStream:AsStream = new AsStream();
				var xmlExamType:XML = new XML( fileStreamExamType.readUTF() );
				
				var examType:ExamType = asStream.fromXml( xmlExamType ) as ExamType;
				
				fileStreamExamType.close();
				
				examType.saved = true;
				
				return examType;
				
			} catch ( e:Error )
			{
				Alert.show( e.toString(), "Error al recuperar examType:"+ examTypeSummary.code );
			}	
			
			return null;
			
		}	
		
		
		
	}
}